<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author XPF
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'physical:sportsPlan:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="60%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #sportsPlanCheckItems="{ model }">
        <a-button class="mt-2" @click="handlesportsPlanCheckItemsAdd(model.adaptGrade,'1')">
          {{ t('添加考核项目（第一学期）') }}
        </a-button>
        <BasicTable
          @register="registersportsPlanCheckItemsTable"
          rowKey="id"
          @row-click="handleTestDataChildRowClick"
        >
          <template #termType="{ text }">
            {{ text==1?dictLabel1:dictLabel2 }}
          </template>
        </BasicTable>
      </template>
      <template #sportsPlanCheckItemsList="{ model }">
        <a-button class="mt-2" @click="handlesportsPlanCheckItemsAdd(model.adaptGrade,'2')">
          {{ t('添加考核项目（第二学期）') }}
        </a-button>
        <BasicTable
          @register="registerPlanCheckItemsTable"
          rowKey="id"
          @row-click="handleTestDataChildRowClick"
          >
          <template #termType="{ text }">
            {{ text==1?dictLabel1:dictLabel2 }}
          </template>
        </BasicTable>
      </template>
    </BasicForm>
  </BasicDrawer>
  <Modal @register="registerModal" @success="handleSuccess" @save="handleSave" />
</template>
<script lang="ts">
export default defineComponent({
  name: 'ViewsPhysicalSportsPlanForm',
});
</script>
<script lang="ts" setup>
import { DictLabel } from '/@/components/Dict';
import { defineComponent, ref, computed } from 'vue';
import { useI18n } from '/@/hooks/web/useI18n';
import { useMessage } from '/@/hooks/web/useMessage';
import { router } from '/@/router';
import moment from 'moment';
import { Icon } from '/@/components/Icon';
import { BasicForm, FormSchema, useForm } from '/@/components/Form';
import { BasicTable, BasicColumn, useTable } from '/@/components/Table';
import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
import { SportsPlan, sportsPlanSave, sportsPlanForm } from '/@/api/physical/sportsPlan';
import { useModal } from '/@/components/Modal';
import Modal from './modal.vue';
import { useDict } from '/@/components/Dict';
import { nextTick } from 'process';
const { initDict, getDictList, getDictLabel } = useDict();
const emit = defineEmits(['success', 'register']);
async function init(data){
  await initDict(data)
};

const dictList = getDictList('s_events_type');

const dictLabel1 = ref();
const dictLabel2 = ref();

const { t } = useI18n('physical.sportsPlan');
const { showMessage } = useMessage();
const sportsPlanCheckItemsListArr = ref([]);
const sportsPlanCheckItemsArr = ref([]);
const record = ref<SportsPlan>({} as SportsPlan);
const getTitle = computed(() => ({
  icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
  value: record.value.isNewRecord ? t('新增体育考核计划') : t('编辑体育考核计划'),
}));
const dataOpen = ref(false);
const inputFormSchemas: FormSchema[] = [
  {
    label: t('适配学年'),
    field: 'adaptAcademicYear',
    component: 'DatePicker',
    componentProps: ({ formModel }) => {
      return {
        mode: 'year',
        // open: dataOpen.value,
        allowClear: true,
        format: 'YYYY',
        disabled: false,
        onChange: (e) => {
          console.log(e);
        },
        // onOpenChange: ()=>{
        //   dataOpen.value = true;
        // },
        onPanelChange: (value) => {
          formModel.adaptAcademicYear = moment(value).format('YYYY');
          // dataOpen.value = false
        },
        onBlurHandle: (e) =>{
          console.log(e)
          // dataOpen.value = false
        },
      };
    },
    required: true,
  },

  {
    label: t('适配年级'),
    field: 'adaptGrade',
    component: 'Select',
    required: true,
    componentProps: {
      dictType: 'vke_grade',
      allowClear: true,
      mode: 'multiple',
    },
  },
  {
    label: t('对应考核项目'),
    field: 'sportsPlanCheckItems',
    component: 'Input',
    slot: 'sportsPlanCheckItems',
  },
  {
    label: t('对应考核项目'),
    field: 'sportsPlanCheckItemsList',
    component: 'Input',
    slot: 'sportsPlanCheckItemsList',
  },
];

const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
  labelWidth: 120,
  schemas: inputFormSchemas,
  baseColProps: { lg: 24, md: 24 },
});
const [registerModal, { openModal }] = useModal();

const [registersportsPlanCheckItemsTable, PlanCheckTable] = useTable({
  actionColumn: {
    width: 60,
    actions: (record: Recordable) => [
      {
        icon: 'ant-design:delete-outlined',
        color: 'error',
        popConfirm: {
          title: '是否确认删除',
          confirm: handleSportsPlanCheckDelete.bind(this, record),
        },
        auth: 'physical:sportsPlan:edit',
      },
    ],
  },
  rowKey: 'id',
  // columns: tableColumns,
  pagination: false,
  bordered: true,
  size: 'small',
  inset: true,
});
const [registerPlanCheckItemsTable, PlanCheckItemsTable] = useTable({
  actionColumn: {
    width: 60,
    actions: (record: Recordable) => [
      {
        icon: 'ant-design:delete-outlined',
        color: 'error',
        popConfirm: {
          title: '是否确认删除',
          confirm: handleSportsPlanCheckItemsDelete.bind(this, record),
        },
        auth: 'physical:sportsPlan:edit',
      },
    ],
  },
  rowKey: 'id',
  // columns: tableColumns,
  pagination: false,
  bordered: true,
  size: 'small',
  inset: true,
});
async function setPlanCheckTableData(_res: Recordable) {
  PlanCheckTable.setColumns([
    {
      title: t('体能/技能项'),
      dataIndex: 'termName',
      align: 'left',
    },
    {
      title: t('类型'),
      dataIndex: 'termType',
      width: 130,
      align: 'left',
      slots: {customRender:'termType'},
    },
    {
      title: t('是否必测项'),
      dataIndex: 'isMandatory',
      width: 130,
      align: 'left',
      dictType: 's_Mandatory',
      editRow: true,
      editComponent: 'Select',
      editComponentProps: {
        dictType: 's_Mandatory',
        allowClear: true,
      },
      editRule: true,
    },
    {
      title: t('*权重'),
      dataIndex: 'weight',
      width: 130,
      align: 'left',
      editRow: true,
      editComponent: 'InputNumber',
      editRule: true,
      editComponentProps: {
        min: '0',
        max: '100',
      },
    },
  ]);
  record.value.sportsPlanCheckItemsList?.forEach((item) => {
    if (item.adaptSemester == 1) {
      sportsPlanCheckItemsArr.value.push({
        id: item.sportsPhysicalSkills.id,
        termName: item.sportsPhysicalSkills.termName,
        termId: item.sportsPhysicalSkills.termId,
        termType: item.sportsPhysicalSkills.termType,
        adaptSemester: 1,
        isMandatory: item.isMandatory,
        weight: item.weight,
        editable: true,
      });
    }
  });
  PlanCheckTable.setTableData(sportsPlanCheckItemsArr.value || []);
}
async function setPlanCheckItemsTableData(_res: Recordable) {
  PlanCheckItemsTable.setColumns([
    {
      title: t('体能/技能项'),
      dataIndex: 'termName',
      align: 'left',
    },
    {
      title: t('类型'),
      dataIndex: 'termType',
      width: 130,
      align: 'left',
      dictType: 's_events_type',
      slots: {customRender:'termType'},
    },
    {
      title: t('是否必测项'),
      dataIndex: 'isMandatory',
      width: 130,
      align: 'left',
      dictType: 's_Mandatory',
      editRow: true,
      editComponent: 'Select',
      editComponentProps: {
        dictType: 's_Mandatory',
        allowClear: true,
      },
      editRule: true,
    },
    {
      title: t('*权重'),
      dataIndex: 'weight',
      width: 130,
      align: 'left',
      editRow: true,
      editComponent: 'InputNumber',
      editRule: true,
      editComponentProps: {
        min: '0',
        max: '100',
      },
    },
  ]);
  record.value.sportsPlanCheckItemsList?.forEach((item) => {
    if (item.adaptSemester == 2) {
      sportsPlanCheckItemsListArr.value.push({
        id: item.sportsPhysicalSkills.id,
        termName: item.sportsPhysicalSkills.termName,
        termId: item.sportsPhysicalSkills.termId,
        termType: item.sportsPhysicalSkills.termType,
        adaptSemester: 2,
        isMandatory: item.isMandatory,
        weight: item.weight,
        editable: true,
      });
    }
  });
  PlanCheckItemsTable.setTableData(sportsPlanCheckItemsListArr.value || []);
}
//
function handleSportsPlanCheckItemsDelete(record: Recordable) {
  PlanCheckItemsTable.deleteTableDataRecord(record.id);
  sportsPlanCheckItemsListArr.value.forEach((item,index) => {
    if(item.id == record.id){
      sportsPlanCheckItemsListArr.value.splice(index,1)
    }
  });
}
function handleSportsPlanCheckDelete(record: Recordable) {
  PlanCheckTable.deleteTableDataRecord(record);
  PlanCheckTable.reload();
  sportsPlanCheckItemsArr.value.forEach((item,index) => {
    if(item.id == record.id){
      sportsPlanCheckItemsArr.value.splice(index,1)
    }
  });
}
function handleTestDataChildRowClick(record: Recordable) {
  record.onEdit?.(true, false);
  record.dataMap = record.dataMap || {};
}

const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  resetFields();
  setDrawerProps({ loading: true });
  const res = await sportsPlanForm(data);
  record.value = (res.sportsPlan || {}) as SportsPlan;
  record.value.__t = new Date().getTime();
  sportsPlanCheckItemsListArr.value = [];
  sportsPlanCheckItemsArr.value = [];
  setPlanCheckTableData(res);
  setPlanCheckItemsTableData(res);
  init(['s_events_type']);
  PlanCheckItemsTable.reload();
  PlanCheckTable.reload();
  setFieldsValue(record.value);
  setTimeout(()=>{
    dictLabel1.value = getDictLabel('s_events_type', '1', '未知');
    dictLabel2.value = getDictLabel('s_events_type', '2', '未知');
    setDrawerProps({ loading: false });
  },500)
});
async function getTestDataChildList(Table) {
    let testDataChildListValid = true;
    let testDataChildList: Recordable[] = [];
    for (const record of Table.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        testDataChildListValid = false;
      }
      testDataChildList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    // for (const record of Table.getDelDataSource()) {
    //   if (!!record.isNewRecord) continue;
    //   testDataChildList.push({
    //     ...record,
    //     status: '1',
    //   });
    // }
    if (!testDataChildListValid) {
      throw new Error('testDataChildList valid.');
    }
    return testDataChildList;
  }
async function handleSubmit() {
  try {
    const data = await validate();
    setDrawerProps({ confirmLoading: true });
    const params: any = {
      isNewRecord: record.value.isNewRecord,
      planId: record.value.planId,
    };
    var arr = <any>[];
    var sportsPlanList = await getTestDataChildList(PlanCheckTable)
    var sportsPlanItemList = await getTestDataChildList(PlanCheckItemsTable)
    var weightTotal1 = 0;
    var weightTotal2 = 0;
    let dataTime = new Date(data.adaptAcademicYear);
    data.adaptAcademicYear = dataTime.getFullYear();
    sportsPlanItemList.forEach((item) => {
      weightTotal1 += item.weight * 1;
      arr.push({
        isMandatory: item.isMandatory,
        termId: item.id,
        // termType: item.termType,
        weight: item.weight,
        adaptSemester: '2',
      });
    });
    sportsPlanList.forEach((item) => {
      weightTotal2 += item.weight * 1;
      arr.push({
        isMandatory: item.isMandatory,
        termId: item.id,
        // termType: item.termType,
        weight: item.weight,
        adaptSemester: '1',
      });
    });
    data.sportsPlanCheckItemsList = arr;
    var weightTotal2Flag = false;
    var weightTotal1Flag = false;
    if (sportsPlanItemList.length == 0) {
      weightTotal1Flag = true;
    }
    if (sportsPlanList.length == 0) {
      weightTotal2Flag = true;
    }
    if (weightJudge(weightTotal1Flag, weightTotal1, weightTotal2Flag, weightTotal2)) {
      const res = await sportsPlanSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } else {
      showMessage('每学期权重总值必须等于100');
    }
  } catch (error: any) {
    if (error && error.errorFields) {
      showMessage(t('您填写的信息有误，请根据提示修正。'));
    }
    console.log('error', error);
  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}
function weightJudge(arrType1, total1, arrType2, total2) {
  let type1 = false;
  let type2 = false;
  if (!arrType1) {
    if (total1 == 100) {
      type1 = true;
    } else {
      type1 = false;
    }
  } else {
    type1 = true;
  }
  if (!arrType2) {
    if (total2 == 100) {
      type2 = true;
    } else {
      type2 = false;
    }
  } else {
    type2 = true;
  }
  return type1 && type2;
}
let sportsPlanCheckId = [];
let sportsPlanCheckArr = [];
function handlesportsPlanCheckItemsAdd(adaptGrade, type) {
  if (type == 1) {
    sportsPlanCheckId = []
    sportsPlanCheckItemsArr.value.forEach((item) => {
      if(sportsPlanCheckId.indexOf(item.id)==-1){
        sportsPlanCheckId.push(item.id);
      }
    });
    sportsPlanCheckArr = sportsPlanCheckItemsArr.value;
  } else {
    sportsPlanCheckId = []
    sportsPlanCheckItemsListArr.value.forEach((item) => {
      if(sportsPlanCheckId.indexOf(item.id)==-1){
        sportsPlanCheckId.push(item.id);
      }
    });
    sportsPlanCheckArr = sportsPlanCheckItemsListArr.value;
  }
  openModal(true, { sportsPlanCheckId, type, sportsPlanCheckArr,adaptGrade });
}
function handleSuccess() {
  // RelationTableReload();
}
function handleSave(options, type) {
  if (type == 1) {
    sportsPlanCheckItemsArr.value = options;
    let value = [];
    options.forEach((item) => {
      var itemArr = {};
      itemArr = {
        id: item.id,
        isMandatory: typeof(item.isMandatory)!='undefined' ? item.isMandatory : 1,
        termName: item.termName,
        termType: item.termType,
        weight: item.weight ? item.weight : '',
        editable: true,
      };
      value.push(itemArr);
    });
    PlanCheckTable.setTableData(value);
  } else {
    sportsPlanCheckItemsListArr.value = options;
    let value = [];
    options.forEach((item) => {
      var itemArr = {};
      itemArr = {
        id: item.id,
        isMandatory: item.isMandatory ? item.isMandatory : '',
        termName: item.termName,
        termType: item.termType,
        weight: item.weight ? item.weight : '',
        editable: true,
      };
      value.push(itemArr);
    });
    PlanCheckItemsTable.setTableData(value);
  }
}
</script>
